package org.ishequ.miduo.weibo;

import java.util.ArrayList;
import java.util.List;

import org.ishequ.miduo.LoginActivity;
import org.ishequ.miduo.R;
import org.ishequ.miduo.R.drawable;
import org.ishequ.miduo.R.id;
import org.ishequ.miduo.R.layout;
import org.ishequ.miduo.MiDuoActivity.ConfigHelper;
import org.ishequ.weibo.adapater.WeiboAdapter;
import org.ishequ.weibo.db.FriendTimelineDBHelper;
import org.ishequ.weibo.domain.UserInfo;
import org.ishequ.weibo.emotion.WeiboEmotion;
import org.ishequ.weibo.utils.InfoHelper;
import org.ishequ.widget.AutoGetMoreListView;
import org.ishequ.widget.WaitingView;

import weibo4android.Comment;
import weibo4android.Count;
import weibo4android.Paging;
import weibo4android.Status;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.WeiboResponse;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class WeiboHomeActivity extends BaseActivity implements OnMenuItemClickListener{

	public static int UNREAD_COMMENT = 1000;
	public static int UNREAD_FOLLOWER = 2000;
	public static int UNREAD_MENTION = 3000;

	private RelativeLayout listviewLayout;
	private UserInfo user = null;
    //显示数据
    private List<WeiboResponse> friendsTimeline = new ArrayList<WeiboResponse>();
    private AutoGetMoreListView autoGetMoreListView;
    private WeiboAdapter adapater;
    private int preIndex = 0;
    
    private int type = 3;
    private WaitingView waitingView;
    private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case InfoHelper.LOADING_DATA_FAILED:
					Toast.makeText(WeiboHomeActivity.this, "获取信息失败",
							Toast.LENGTH_LONG).show();
					WeiboHomeActivity.this.finish();
					break;
				case InfoHelper.LOADING_DATA_COMPLETED:
					adapater.notifyDataSetChanged();
					waitingView.setVisibility(View.GONE);
					autoGetMoreListView.setVisibility(View.VISIBLE);
					FriendTimelineDBHelper.getInstance(WeiboHomeActivity.this)
							.saveFriendTimeline(friendsTimeline);
					autoGetMoreListView.setSelection(1);
//					Toast.makeText(WeiboHomeActivity.this, "刷新首页微博完成",
//							Toast.LENGTH_LONG).show();
					break;
				case WeiboEmotion.EMOTIONS_DOWNLOAD_COMPLETED:
					Toast.makeText(WeiboHomeActivity.this, "表情包下载或更新完毕",
							Toast.LENGTH_LONG).show();
					break;
				case WeiboEmotion.EMOTIONS_DOWNLOAD_FAILED:
					Toast.makeText(WeiboHomeActivity.this, "表情包下载或更新失败",
							Toast.LENGTH_LONG).show();
					break;

			}
		}
	};


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(
				R.layout.weibo_home, null);
		root.addView(layout);
		
		// 设置标题栏文字
		titlebarText.setText("浏览微博");
		
		listviewLayout = (RelativeLayout)layout.findViewById(R.id.listviewLayout);
		user = ConfigHelper.nowUser;
		waitingView = new WaitingView(this);
		
		autoGetMoreListView = new AutoGetMoreListView(this);
		adapater = new WeiboAdapter(this, R.layout.weibo_item_weibo, friendsTimeline, type,autoGetMoreListView);
		autoGetMoreListView.setAdapter(adapater);
		autoGetMoreListView.setOnGetMoreListener(adapater);
		autoGetMoreListView.setOnRefreshListener(adapater);
		autoGetMoreListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(WeiboHomeActivity.this,WeiboViewActivity.class);
				intent.putExtra("cid",((Status) friendsTimeline.get(position - 1)).getId());
				startActivityForResult(intent, 1);
			}
		});
		
		listviewLayout.addView(waitingView);
		listviewLayout.addView(autoGetMoreListView);
		autoGetMoreListView.setVisibility(View.GONE);
		 //初始化数据
		iniData();
	}

	private void iniData() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Weibo weibo = new Weibo();
					weibo.setToken(user.getToken(), user.getTokenSecret());
					friendsTimeline.addAll(weibo.getFriendsTimeline());
					handler.sendEmptyMessage(InfoHelper.LOADING_DATA_COMPLETED);
				} catch (WeiboException e) {
					e.printStackTrace();
					handler.sendEmptyMessage(InfoHelper.LOADING_DATA_FAILED);
				}
				unReadNotify(WeiboHomeActivity.this);
			}
		}).start();
	}
	
	
	public static void unReadNotify(Context context) {
		Count unread_count;
		try {
			Weibo weibo = new Weibo();
			weibo.setToken(ConfigHelper.nowUser.getToken(), ConfigHelper.nowUser.getTokenSecret());
			unread_count = weibo.getUnread();
			NotificationManager notificationManager = (NotificationManager) context
					.getSystemService(NOTIFICATION_SERVICE);
			if (unread_count.getComments() != 0) {
				Notification notification = new Notification(R.drawable.weibo_image,
						"你有" + unread_count.getComments() + "条未读评论.",
						System.currentTimeMillis());
				Intent intent = new Intent(context, WeiboInfoActivity.class);
				intent.putExtra("type", 0);
				PendingIntent contentIntent = PendingIntent.getActivity(
						context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
				notification.setLatestEventInfo(context,
						"你有" + unread_count.getComments() + "条未读评论.", "",
						contentIntent);
				notification.defaults = Notification.DEFAULT_ALL;
				notificationManager.notify(UNREAD_COMMENT, notification);
			}
			if (unread_count.getMentions() != 0) {
				Notification notification = new Notification(R.drawable.weibo_image,
						"你有" + unread_count.getMentions() + "条未读@你的微薄.",
						System.currentTimeMillis());
				Intent intent = new Intent(context, WeiboInfoActivity.class);
				intent.putExtra("type", 2);
				PendingIntent contentIntent = PendingIntent.getActivity(
						context, UNREAD_MENTION, intent,
						PendingIntent.FLAG_UPDATE_CURRENT);
				notification.setLatestEventInfo(context,
						"你有" + unread_count.getMentions() + "条未读@你的微薄.", "",
						contentIntent);
				notification.defaults = Notification.DEFAULT_ALL;
				notificationManager.notify(UNREAD_MENTION, notification);
			}
			if (unread_count.getFollowers() != 0) {
				Notification notification = new Notification(R.drawable.weibo_image,
						"你有" + unread_count.getFollowers() + "新的关注者.",
						System.currentTimeMillis());
				Intent intent = new Intent(context, WeiboFriendsOrFollowsListActivity.class);
				intent.putExtra("flag", true);
				PendingIntent contentIntent = PendingIntent.getActivity(
						context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
				notification.setLatestEventInfo(context,
						"你有" + unread_count.getFollowers() + "新的关注者.", "",
						contentIntent);
				notification.defaults = Notification.DEFAULT_ALL;
				notificationManager.notify(UNREAD_FOLLOWER, notification);
			}

			if (unread_count.getDm() != 0) {
				Notification notification = new Notification(R.drawable.weibo_image,
						"你有" + unread_count.getDm() + "条未读的私信.",
						System.currentTimeMillis());
				Intent intent = new Intent(context, LoginActivity.class);
				PendingIntent contentIntent = PendingIntent.getActivity(
						context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
				notification.setLatestEventInfo(context,
						"你有" + unread_count.getDm() + "条未读的私信.", "",
						contentIntent);
				notification.defaults = Notification.DEFAULT_ALL;
				notificationManager.notify(UNREAD_FOLLOWER, notification);
			}
		} catch (WeiboException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onMenuItemClick(MenuItem item) {
		switch (item.getItemId()) {
		case 4:
			Toast.makeText(WeiboHomeActivity.this, "开始下载表情包，请稍候...",
					Toast.LENGTH_LONG).show();
			new Thread(new Runnable() {

				@Override
				public void run() {
					WeiboEmotion.downloadEmotions(handler);
				}
			}).start();
			return true;
		case 5:
			Toast.makeText(WeiboHomeActivity.this, "开始更新表情包，请稍候...",
					Toast.LENGTH_LONG).show();
			new Thread(new Runnable() {

				@Override
				public void run() {
					WeiboEmotion.updateEmotions(handler);
				}
			}).start();
			return true;
	}
	return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(1, 1, 1, "发微博").setIntent(
				new Intent(this, WeiboShareActivity.class));
		Intent intent1 = new Intent(this, WeiboFriendsOrFollowsListActivity.class);
		intent1.putExtra("flag", false);
		menu.add(1, 2, 2, "已关注的人").setIntent(intent1);
		Intent intent2 = new Intent(this, WeiboFriendsOrFollowsListActivity.class);
		intent2.removeExtra("flag");
		intent2.putExtra("flag", true);
		menu.add(1, 3, 3, "粉丝").setIntent(intent2);
		menu.add(1, 4, 4, "下载表情包").setOnMenuItemClickListener(this);
		menu.add(1, 5, 5, "更新表情包").setOnMenuItemClickListener(this);
		return true;
	}
	//startActivityForResult 获得result后执行的
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
//		tabHost.setCurrentTab(preIndex);
	}
	
	
}
